package com.tang.mybatis.executor.resultset;

import com.tang.mybatis.mapping.MappedStatement;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Tang
 * @classname DefaultResultSetHandler
 * @description [  ]
 * @date 2022/4/8 22:41
 */
public class DefaultResultSetHandler implements ResultSetHandler {

    private MappedStatement mappedStatement;

    public DefaultResultSetHandler(MappedStatement mappedStatement) {
        this.mappedStatement = mappedStatement;
    }

    public <E> List<E> handleResultSets(ResultSet resultSet) {
        List<E> result = new ArrayList<>();
        if (null == resultSet) {
            return null;
        }
        try {
            while (resultSet.next()) {
                Class<?> entityClass = Class.forName(mappedStatement.getResultType());
                E entity = (E) entityClass.newInstance();
                for (Field field : entityClass.getDeclaredFields()) {

                    field.setAccessible(true);
                    Class<?> type = field.getType();

                    if (String.class.equals(type)) {
                        field.set(entity, resultSet.getString(field.getName()));
                    }else if (int.class.equals(type) || Integer.class.equals(type)) {
                        field.set(entity, resultSet.getInt(field.getName()));
                    } else {
                        // 其他类型自己转换，这里就直接设置了
                        field.set(entity, resultSet.getObject(field.getName()));
                    }
                    result.add(entity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}